/**
 * OCR识别记录服务
 * 对接后端OCR识别记录API
 */

import apiClient from './api'

// OCR记录接口定义
export interface OCRRecord {
  id: string
  type: 'drug_info' | 'medical_id' | 'document' | 'general'
  fileName: string
  text: string
  confidence: number
  success: boolean
  serviceType: 'tesseract' | 'ppocr' | 'baidu' | 'aliyun' | 'mock'
  processingTime: number
  drugInfo?: {
    name: string
    specification: string
    manufacturer: string
    batchNumber: string
    expiryDate: string
    approvalNumber: string
    category: string
    indication: string
  }
  createdAt: string
  userId: string
}

export interface OCRStats {
  totalRecords: number
  successCount: number
  successRate: number
  avgProcessingTime: number
  serviceTypeStats: Record<string, number>
}

export interface PaginationInfo {
  page: number
  limit: number
  total: number
}

export interface GetHistoryParams {
  userId?: string
  page?: number
  limit?: number
  ocrType?: string
}

export interface GetHistoryResponse {
  success: boolean
  data: OCRRecord[]
  pagination: PaginationInfo
  error?: string
}

export interface GetStatsResponse {
  success: boolean
  data: OCRStats
  error?: string
}

export interface DeleteRecordResponse {
  success: boolean
  message: string
  error?: string
}

/**
 * OCR记录服务类
 */
class OCRRecordService {
  private baseUrl = '/api/ocr'

  /**
   * 获取OCR识别历史记录
   * @param params 查询参数
   * @returns Promise<GetHistoryResponse>
   */
  async getHistory(params: GetHistoryParams = {}): Promise<GetHistoryResponse> {
    try {
      const {
        userId = 'system_user',
        page = 1,
        limit = 20,
        ocrType = ''
      } = params

      console.log('获取OCR历史记录:', { userId, page, limit, ocrType })

      const queryParams = new URLSearchParams({
        userId,
        page: page.toString(),
        limit: limit.toString()
      })

      if (ocrType) {
        queryParams.append('ocrType', ocrType)
      }

      const response = await apiClient.get(`${this.baseUrl}/history?${queryParams}`)

      if (response.data.success) {
        console.log('获取OCR历史成功:', response.data.data.length, '条记录')
        return {
          success: true,
          data: response.data.data.map(this.formatRecord),
          pagination: response.data.pagination
        }
      } else {
        throw new Error(response.data.message || '获取历史记录失败')
      }
    } catch (error) {
      console.error('获取OCR历史记录失败:', error)
      return {
        success: false,
        data: [],
        pagination: { page: 1, limit: 20, total: 0 },
        error: error instanceof Error ? error.message : '获取历史记录失败'
      }
    }
  }

  /**
   * 获取OCR识别统计信息
   * @param userId 用户ID
   * @returns Promise<GetStatsResponse>
   */
  async getStats(userId = 'system_user'): Promise<GetStatsResponse> {
    try {
      console.log('获取OCR统计信息:', userId)

      const response = await apiClient.get(`${this.baseUrl}/stats`, {
        params: { userId }
      })

      if (response.data.success) {
        const stats = response.data.data
        return {
          success: true,
          data: {
            totalRecords: stats.totalRecords || 0,
            successCount: stats.successCount || 0,
            successRate: Math.round((stats.successRate || stats.successCount / Math.max(stats.totalRecords, 1)) * 100) / 100,
            avgProcessingTime: Math.round(stats.avgProcessingTime || 0),
            serviceTypeStats: stats.serviceTypeStats || {}
          }
        }
      } else {
        throw new Error(response.data.message || '获取统计信息失败')
      }
    } catch (error) {
      console.error('获取OCR统计信息失败:', error)
      return {
        success: false,
        data: {
          totalRecords: 0,
          successCount: 0,
          successRate: 0,
          avgProcessingTime: 0,
          serviceTypeStats: {}
        },
        error: error instanceof Error ? error.message : '获取统计信息失败'
      }
    }
  }

  /**
   * 删除OCR识别记录
   * @param recordId 记录ID
   * @returns Promise<DeleteRecordResponse>
   */
  async deleteRecord(recordId: string): Promise<DeleteRecordResponse> {
    try {
      console.log('删除OCR记录:', recordId)

      const response = await apiClient.delete(`${this.baseUrl}/history/${recordId}`)

      if (response.data.success) {
        console.log('OCR记录删除成功')
        return {
          success: true,
          message: response.data.message || '删除成功'
        }
      } else {
        throw new Error(response.data.message || '删除记录失败')
      }
    } catch (error) {
      console.error('删除OCR记录失败:', error)
      return {
        success: false,
        message: '',
        error: error instanceof Error ? error.message : '删除记录失败'
      }
    }
  }

  /**
   * 清除指定用户的所有记录
   * @param userId 用户ID
   * @returns Promise<DeleteRecordResponse>
   */
  async clearUserRecords(userId = 'system_user'): Promise<DeleteRecordResponse & { deletedCount?: number }> {
    try {
      console.log('清除用户OCR记录:', userId)

      // 先获取用户的所有记录
      const historyResult = await this.getHistory({ userId, limit: 1000 })
      
      if (historyResult.success && historyResult.data.length > 0) {
        // 逐个删除记录
        let deletedCount = 0
        for (const record of historyResult.data) {
          const deleteResult = await this.deleteRecord(record.id)
          if (deleteResult.success) {
            deletedCount++
          }
        }

        return {
          success: true,
          message: `已清除 ${deletedCount} 条记录`,
          deletedCount
        }
      } else {
        return {
          success: true,
          message: '没有记录需要清除',
          deletedCount: 0
        }
      }
    } catch (error) {
      console.error('清除用户OCR记录失败:', error)
      return {
        success: false,
        message: '',
        error: error instanceof Error ? error.message : '清除记录失败'
      }
    }
  }

  /**
   * 上传文件进行OCR识别
   * @param file 文件对象
   * @param options 识别选项
   * @returns Promise<any>
   */
  async recognizeDrug(file: File, options: { parallel?: boolean } = {}): Promise<any> {
    try {
      console.log('开始药品OCR识别:', file.name)

      const formData = new FormData()
      formData.append('image', file)
      
      if (options.parallel) {
        formData.append('parallel', 'true')
      }

      const response = await apiClient.post(`${this.baseUrl}/recognize/drug`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 60000 // 60秒超时
      })

      if (response.data.success) {
        console.log('OCR识别成功:', response.data.data)
        return {
          success: true,
          data: {
            originalFile: response.data.data.originalFile,
            text: response.data.data.text || '',
            confidence: response.data.data.confidence || 0,
            drugInfo: response.data.data.drugInfo || {},
            recognitionMode: response.data.data.recognitionMode || 'single',
            words: response.data.data.words || [],
            serviceUsed: this.getServiceName(response.data.message || '')
          },
          message: response.data.message
        }
      } else {
        throw new Error(response.data.message || 'OCR识别失败')
      }
    } catch (error) {
      console.error('药品OCR识别失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : 'OCR识别失败',
        data: null
      }
    }
  }

  /**
   * 通用文字识别
   * @param file 文件对象
   * @returns Promise<any>
   */
  async recognizeGeneral(file: File): Promise<any> {
    try {
      console.log('开始通用文字识别:', file.name)

      const formData = new FormData()
      formData.append('image', file)

      const response = await apiClient.post(`${this.baseUrl}/recognize`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 60000
      })

      if (response.data.success) {
        console.log('文字识别成功:', response.data.data)
        return {
          success: true,
          data: {
            originalFile: response.data.data.originalFile,
            text: response.data.data.text || '',
            confidence: response.data.data.confidence || 0,
            words: response.data.data.words || [],
            serviceUsed: this.getServiceName(response.data.message || '')
          },
          message: response.data.message
        }
      } else {
        throw new Error(response.data.message || '文字识别失败')
      }
    } catch (error) {
      console.error('通用文字识别失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '文字识别失败',
        data: null
      }
    }
  }

  /**
   * 格式化记录数据
   * @param record 原始记录数据
   * @returns OCRRecord 格式化后的记录
   */
  private formatRecord(record: any): OCRRecord {
    return {
      id: record.id,
      type: record.type,
      fileName: record.fileName,
      text: record.text,
      confidence: Math.round((record.confidence || 0) * 100),
      success: record.success,
      serviceType: record.serviceType,
      processingTime: record.processingTime,
      drugInfo: record.drugInfo,
      createdAt: this.formatTime(record.createdAt),
      userId: record.userId
    }
  }

  /**
   * 解析服务名称
   * @param message 返回消息
   * @returns string 服务名称
   */
  private getServiceName(message: string): string {
    if (message.includes('百度AI')) return 'baidu'
    if (message.includes('阿里云')) return 'aliyun'
    if (message.includes('Tesseract')) return 'tesseract'
    if (message.includes('PP-OCR')) return 'ppocr'
    if (message.includes('演示模式')) return 'mock'
    return 'tesseract'
  }

  /**
   * 格式化时间显示
   * @param timeString 时间字符串
   * @returns string 格式化后的时间
   */
  private formatTime(timeString: string): string {
    try {
      const date = new Date(timeString)
      const now = new Date()
      const diffMs = now.getTime() - date.getTime()
      const diffMinutes = Math.floor(diffMs / (1000 * 60))
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

      if (diffMinutes < 1) {
        return '刚刚'
      } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`
      } else if (diffHours < 24) {
        return `${diffHours}小时前`
      } else if (diffDays < 7) {
        return `${diffDays}天前`
      } else {
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: 'numeric',
          day: 'numeric',
          hour: 'numeric',
          minute: 'numeric'
        })
      }
    } catch (error) {
      console.error('时间格式化失败:', error)
      return timeString || '未知时间'
    }
  }

  /**
   * 格式化OCR类型显示文本
   * @param type OCR类型
   * @returns string 格式化后的类型
   */
  formatOCRType(type: string): string {
    const typeMap: Record<string, string> = {
      'drug_info': '药物识别',
      'medical_id': '医生认证', 
      'document': '文档识别',
      'general': '通用识别'
    }
    return typeMap[type] || type || '未知类型'
  }

  /**
   * 格式化服务类型显示文本
   * @param serviceType 服务类型
   * @returns string 格式化后的服务类型
   */
  formatServiceType(serviceType: string): string {
    const serviceMap: Record<string, string> = {
      'tesseract': 'Tesseract.js',
      'ppocr': 'PP-OCR',
      'baidu': '百度AI',
      'aliyun': '阿里云',
      'mock': '演示模式'
    }
    return serviceMap[serviceType] || serviceType || '未知'
  }
}

// 创建单例实例
export const ocrService = new OCRRecordService()
export default ocrService